package erp_services

import (
	"errors"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/global"
)

type mixingStationService struct {
}

var MixingStationService = new(mixingStationService)

// 新增
func (mixingStationService *mixingStationService) Create(ms erp_models.MixingStation) (uint, error) {
	result := global.App.DB.Create(&ms)
	if result.Error != nil {
		return 0, result.Error
	}
	return ms.ID.ID, nil
}

func (mixingStationService *mixingStationService) Update(ms erp_models.MixingStation) (err error) {
	if err := global.App.DB.Model(&erp_models.MixingStation{}).Where("ID = ?", ms.ID.ID).Updates(&ms).Error; err != nil {
		return err
	}
	return nil
}

// 根据生产线查询项目编号
func (mixingStationService *mixingStationService) GetXMID(production_no string) (xmid string) {
	sqlstr := ` 
			SELECT pound_scale 
			FROM mixing_station 
			WHERE 
			IF (
			INSTR(production_line, ',') > 0,
			FIND_IN_SET(
				(
					SELECT
						id
					FROM
						production_line
					WHERE
						production_no = ?
				),
				production_line
			) > 0,
			production_line = (
				SELECT
					id
				FROM
					production_line
				WHERE
					production_no = ?
			)
			)
		`
	global.App.DB.Raw(sqlstr, production_no, production_no).Scan(&xmid)
	return
}

func (mixingStationService *mixingStationService) GetXMIDByStationId(station_id int64) (ms *erp_models.MixingStation, err error) {
	err = global.App.DB.First(&ms, station_id).Error
	if err != nil || ms.ID.ID == 0 {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}
